<?php
/**
 * 表数据，整表缓存
 *
 * @author  Dr. Dragon
 * @explain 子类需指定 table
 *
 */

namespace dragon\Cache;

use think\Cache;
use think\Db;

abstract class TableCache
{

    public static $table = null;
    public static $dataKey = 'id';
    public static $all = null;

    // 数据格式化
    public static function format($list)
    {
        $_list = [];
        foreach ($list as $key => $val) {
            $_list[$val[static::$dataKey]] = $val;
        }
        return $_list;
    }

    // 获取所有数据
    public static function all()
    {

        if (static::$all = Cache::get(static::class)) return static::$all;

        return Cache::remember(static::class, function () {
            $list = Db::name(static::$table)->order('`list_order` asc')->select()->toArray();
            return static::$all = static::format($list);
        });
    }


    // 获取单条数据
    public static function get($key)
    {
        $all = static::all();
        return $all[$key];
    }

    // 清除缓存
    public static function clear()
    {
        static::$all = null;
        Cache::set(static::class, null);
    }

    // 添加
    public static function add($data)
    {
        static::clear();
        return Db::name(static::$table)->insertGetId($data);
    }

    // 修改
    public static function save($condition, $data)
    {
        static::clear();
        $map = $condition;
        is_numeric($map) and $map = ['id' => $condition];
        return Db::name(static::$table)->where($map)->update($data);
    }

    // 删除
    public static function del($condition)
    {
        static::clear();
        $map = $condition;
        is_numeric($map) and $map = ['id' => $condition];
        return Db::name(static::$table)->where($condition)->delete();
    }
}
